/*
 *
 *  Copyright (C) 2008-2010 GSyC/LibreSoft, Universidad Rey Juan Carlos
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App;

import java.io.File;
import java.io.FileOutputStream;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Photo;
import com.LibreGeoSocial.App.Routes.LocationService;
import com.LibreGeoSocial.App.Utils.LocationUtils;


public class VideoCard extends GenericCard {

	
	private ImageView imageVideo;
	private TextView lbTitle, lbBody, lbDate, lbDist, lbUploader;
	private ScrollView lbscroll;
	private Photo mVideo;
	private String nameFile;
	
	private static final int MENU_AVATAR = Menu.FIRST + 10;
	private static final int MENU_SHARE = Menu.FIRST + 20;
	private static final int MENU_OPEN = Menu.FIRST + 30;

	
    public void onCreate(Bundle icicle) {
    	
         super.onCreate(icicle);
         
         setContentView(R.layout.generic_card);
         
         OnClickListener showVideo = new OnClickListener() {
       		public void onClick(View view) {
       			loadVideo();
       		}
       	 };
       	 
         mVideo = (Photo) mNode;
         
         imageVideo = (ImageView)this.findViewById(R.id.img);
         imageVideo.setClickable(true);
         imageVideo.setOnClickListener(showVideo);

         lbscroll = (ScrollView) this.findViewById(R.id.ScrollView01);
         lbTitle = (TextView) this.findViewById(R.id.lbTitle);
         lbBody = (TextView) this.findViewById(R.id.lbBody);   
         lbDate = (TextView) this.findViewById(R.id.lbDate);
         lbDist = (TextView) this.findViewById(R.id.lbDist);
         lbUploader = (TextView) this.findViewById(R.id.lbUploader);

         
         lbTitle.setText (mVideo.getName());
         lbBody.setText  (mVideo.getDescription());
         lbDate.setText  ("Date: " + mVideo.getSince().split(" ")[0]); 
         
         // Calculate distance
         float dist = LocationUtils.calculateDistance (LocationService.getCurrentLocation(),
        		 	mVideo.getLocation());
         
         lbDist.setText  ("Distance: " + LocationUtils.displayDistance(dist, LocationUtils.AUTO));
         
         lbUploader.setText  ("by: " + mVideo.getUploader());

         
         imageVideo.setImageBitmap(mVideo.getBitmapImageThumb());
         
         nameFile = mVideo.getName().replace(" ", "_").replace("/","_").replace(".","_").replace(",","_");
         
         setIconId(R.drawable.image_48);
         showMap(mVideo.getLongitude(), mVideo.getLatitude());
         
    }

	private void loadVideo() {

		String tmp_path = getResources().getString(R.string.tmp_path);
		String name = mVideo.getName();
		String url = mVideo.getUrl();
				
		//Bitmap bitmap = mVideo.getBitmapImageMedium();
	
		//create the dir if not exists
        
		File dirhandler = new File (tmp_path);
        if(! dirhandler.exists())
          dirhandler.mkdirs();

        try {
            //FileOutputStream out = new FileOutputStream( tmp_path + "LGS_" + nameFile + ".jpeg");
            //FileOutputStream out = new FileOutputStream( tmp_path + "LGS_Photo" + ".jpeg");

            //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
         	//out.flush();
            //out.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }
		
    	Intent i = new Intent(android.content.Intent.ACTION_VIEW);
        
    	//i.setDataAndType(Uri.fromFile(new File(tmp_path + "LGS_" + nameFile + ".jpeg")), "image/jpeg");
    	//i.setDataAndType(Uri.fromFile(new File(tmp_path + "LGS_Photo" + ".jpeg")), "image/jpeg");

    	startActivity(i);
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        super.onCreateOptionsMenu(menu);
        
        menu.add(0, MENU_AVATAR, 0, "Set as Avatar")
        		.setIcon(R.drawable.users_two_38)
                .setAlphabeticShortcut('A');
        
        menu.add(0, MENU_SHARE, 0, "Share")
                .setAlphabeticShortcut('B')
        		.setIcon(R.drawable.up);

        menu.add(0, MENU_OPEN, 0, "Open Photo")
        		.setAlphabeticShortcut('C')
        		.setIcon(R.drawable.image_48);

        
        

        
        return true;
	}
	
    @Override
    public boolean onOptionsItemSelected (MenuItem item) {

    	switch (item.getItemId()) {
    	
    		case MENU_AVATAR:
    			
    			if (LibreGeoSocial.getInstance().setAvatar(mVideo.getId()))
    				Toast.makeText(getBaseContext(), 
    	                    "Set this photo as your avatar!", 
    	                    Toast.LENGTH_LONG).show();
    			else
    				Toast.makeText(getBaseContext(), 
    	                    "Error! Can't set photo as your avatar!!", 
    	                    Toast.LENGTH_LONG).show();
    			
    			
    			break;
    			
    		case MENU_OPEN:
    			
    			loadVideo();
    			break;
    		
    		case MENU_SHARE:

    			String tmp_path = getResources().getString(R.string.tmp_path);

                //create the dir if not exists
                File dirhandler = new File (tmp_path);
                if(! dirhandler.exists())
                  dirhandler.mkdirs();

                try {
                    FileOutputStream out = new FileOutputStream( tmp_path + "LGS_" + nameFile + ".jpeg");
                    //FileOutputStream out = new FileOutputStream( tmp_path + "LGS_Pĥoto" + ".jpeg");

                    mVideo.getBitmapImageMedium().compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent i = new Intent(Intent.ACTION_SEND);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //i.putExtra(Intent.EXTRA_TEXT, mPhoto.getDescription());
                i.putExtra(Intent.EXTRA_TEXT, tmp_path + "LGS_" + nameFile + ".jpeg");
                
                i.setType("image/jpeg");
                i.putExtra(Intent.EXTRA_SUBJECT, "[LGS-Photo] " + mVideo.getName());
                i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File( tmp_path + "LGS_" + nameFile + ".jpeg")));
                //i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File( tmp_path + "LGS_Pĥoto" + ".jpeg")));

                startActivity(i);

    	}

    	return super.onOptionsItemSelected(item);
    }	

}